package com.fast.develop.core.web;

import cn.hutool.core.util.StrUtil;
import com.fast.develop.core.properties.DomainRuntimeProperties;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Method;

/**
 * @author 莫寅
 * @createTime 2022-06-18 05:38
 * @desc：
 */
@Slf4j
public abstract class AbstractMappingRegistor implements MappingRegistor {


    private MappingHandlerMapping mappingHandlerMapping;
    private DomainRuntimeProperties domainRuntimeProperties;
    private Object objectHandler;

    public AbstractMappingRegistor(MappingHandlerMapping mappingHandlerMapping, DomainRuntimeProperties domainRuntimeProperties, Object objectHandler) {
        this.mappingHandlerMapping = mappingHandlerMapping;
        this.domainRuntimeProperties = domainRuntimeProperties;
        this.objectHandler = objectHandler;
    }

    private String getPrefix(){
        String apiPrefix = "";
        if(domainRuntimeProperties != null && StrUtil.isNotBlank(domainRuntimeProperties.getApiPrefix())){
            apiPrefix = StrUtil.isNotBlank(domainRuntimeProperties.getApiPrefix()) ? domainRuntimeProperties.getApiPrefix() : "";
        }
        apiPrefix += getKey();
        return apiPrefix;
    }

    protected String getPath(String path){
        String prefix = getPrefix();
        if(prefix.charAt(prefix.length()-1) == StrUtil.SLASH.charAt(0)){
            prefix = prefix.substring(0, prefix.length()-2);
        }

        if(StrUtil.isBlank(path)){
            return prefix;
        }

        if(path.charAt(0) == StrUtil.SLASH.charAt(0)){
            path = path.substring(1, path.length()-1);
        }

        return prefix + StrUtil.SLASH + path;
    }


    protected void registerMapping(MappingInfo resourcesInfo, Method method){
        try{
            mappingHandlerMapping.registerMapping(resourcesInfo, objectHandler, method);
        }catch (Exception e){
//            log.warn("mapping已存在！不能重复注册：{}", resourcesInfo);
        }
    }


    protected void unRegisterMapping(MappingInfo requestMappingInfo){
        try{
            mappingHandlerMapping.unRegisterMapping(requestMappingInfo);
        }catch (Exception e){
            log.warn("mapping已不存在！{}", requestMappingInfo);
        }
    }

    protected abstract String getKey();

    public MappingHandlerMapping getMappingHandlerMapping() {
        return mappingHandlerMapping;
    }
}
